package com.changgou.controller;

import com.changgou.file.FastDFSFile;
import com.changgou.util.FastDFSClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * FastDFS文件上传下载等
 * @author zhengjd
 * @date 2020/5/2 9:36
 */
@RestController
@CrossOrigin
public class FileController {

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("upload")
    public String upload(@RequestParam("file")MultipartFile file){
        try {
            //封装一个FastDFSFile对象
            FastDFSFile fastDFSFile = new FastDFSFile(file.getOriginalFilename(),
                    file.getBytes(),
                    StringUtils.getFilenameExtension(file.getOriginalFilename()));

            //调用上传文件工具类
            String[] strings = FastDFSClient.upload(fastDFSFile);
            //组装上传文件的地址
            return FastDFSClient.getTrackerUrl()+"/"+strings[0]+"/"+strings[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
